import {createServer} from "http";
import {readFile} from "fs";
import {fetchHtml} from "./fetch.js";
import {writeFile} from "fs/promises";
import {listFolder, uploadObject} from './obsutil.js'
import {web_config, obs_config} from '../config.js'

function extractParams(url) {
  return new URL(url, 'http://localhost').searchParams
}

createServer((req, res) => {
  const {url, method} = req
  if (url === '/' && method === 'GET') {
    readFile('src/index.html', (err, data) => {
      if (err) {
        res.writeHead(500, {'Content-Type': 'text/html; charset=utf-8'})
        res.end('<h1>服务器出了点小问题〒▽〒</h1>')
        return
      }
      res.writeHead(200, {'Content-Type': 'text/html'})
      res.write(data)
      res.end()
    })
  } else {
    let urlSearchParams = extractParams(url)
    if (url.startsWith('/search')) {
      let paramUrl = urlSearchParams.get('url')
      if (paramUrl === null) {
        res.writeHead(200, {'Content-Type': 'application/json'})
        res.write(JSON.stringify({
          code: 400,
          data: '参数错误！请重新输入！'
        }))
        res.end()
        return
      }
      const folder = paramUrl.replaceAll(/https:\/\/|http:\/\//g, '')
      const file = `./temp/${folder}-${new Date().toLocaleString('zh-CN', {
        hour12: false,
        year: 'numeric',
        day: '2-digit',
        month: '2-digit',
        hour: 'numeric',
        minute: '2-digit',
        second: '2-digit'
      }).replaceAll(/\/|\s|:/g, '')}.html`
      fetchHtml(paramUrl)
        .then(dom => {
          return writeFile(
            file,
            dom.serialize())
        })
        .then(() => {
          return uploadObject(file, folder)
        })
        .then((result) => {
          if (result.CommonMsg.Status < 300) {
            if (result.InterfaceResult) {
              res.writeHead(200, {'Content-Type': 'application/json'})
              res.write(JSON.stringify({
                code: 200,
                data: '快照捕捉成功！'
              }))
              res.end()
            }
          } else {
            res.writeHead(200, {'Content-Type': 'application/json'})
            res.write(JSON.stringify({
              code: 501,
              data: '快照上传失败！' + result.CommonMsg.Message
            }))
            res.end()
          }
        })
        .catch(reason => {
          console.log(reason)
          res.writeHead(200, {'Content-Type': 'application/json'})
          res.write(JSON.stringify({
            code: 502,
            data: '快照获取失败或保存失败！'
          }))
          res.end()
        })
        .finally(() => {
          // @todo: 删除 temp 文件
        })
    }
    else if (url.startsWith('/list')) {
      const paramUrl = urlSearchParams.get('url')
      const paramPage = urlSearchParams.get('page')
      if (paramUrl === null || paramPage === null) {
        res.writeHead(200, {'Content-Type': 'application/json'})
        res.write(JSON.stringify({
          code: 400,
          data: '参数错误！请重新输入！'
        }))
        res.end()
        return
      }
      const folder = paramUrl.replaceAll(/https:\/\/|http:\/\//g, '')
      listFolder(folder)
        .then((result) => {
          if (result.CommonMsg.Status < 300) {
            if (result.InterfaceResult) {
              const links = result.InterfaceResult.Contents.flatMap((value => {
                if (value.Key.endsWith('/')) return []
                // return ['https://web-page-snapshot.obs.cn-north-1.myhuaweicloud.com/' + value.Key]
                return [`https://${obs_config.bucket}.${obs_config.server}/` + value.Key]
              }))
              res.writeHead(200, {'Content-Type': 'application/json'})
              res.write(JSON.stringify({
                code: 200,
                data: {
                  total: links.length,
                  pageLinks: links.slice((paramPage - 1) * 5, paramPage * 5)
                }
              }))
              res.end()
            }
          } else {
            res.writeHead(200, {'Content-Type': 'application/json'})
            res.write(JSON.stringify({
              code: 501,
              data: '获取快照列表失败！' + result.CommonMsg.Message
            }))
            res.end()
          }
        })
        .catch((reason) => {
          console.log(reason)
          res.writeHead(200, {'Content-Type': 'application/json'})
          res.write(JSON.stringify({
            code: 502,
            data: '获取遇到未知错误！请联系管理员！'
          }))
          res.end()
        })
        .finally(() => {
          // @todo: 删除 temp 文件
        })
    }
    else if (url.startsWith('/img')) {
      readFile('./' + url, (err, data) => {
        if (err) {
          res.writeHead(500)
          res.end()
          return
        }
        res.writeHead(200, {'Content-Type': 'image/*'})
        res.write(data)
        res.end()
      })
    }
    else {
      res.writeHead(400, {'Content-Type': 'text/html; charset=utf-8'})
      res.write('你走丢了')
      res.end()
    }
  }
})
  .listen(web_config.port, () => {
    console.log('server is running at http://localhost!')
  })
